package org.ggumm21.moneybook;

import javax.persistence.Id;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
import com.googlecode.objectify.annotation.Cached;

@Cached
public class BookConfiguration {

	@Id private Long id;
	private String name;
	private String applyYm;
	private String value;
	private String desc;
	
	@SuppressWarnings("unused")
	private BookConfiguration() {
		
	}
	
	public BookConfiguration(String name) {
		this(name, null, null);
		
	}
	
	public BookConfiguration(String name, String value) {
		this(name, value, null);
	}
	
	public BookConfiguration(String name, String value, String applyYm) {
		this.name = name;
		if (value == null)
			this.value = BookManager.getDefaultConfValue(name);
		else
			this.value = value;
		if (BookManager.getDependsOnTimeConfValue(name) && applyYm == null)
			this.applyYm = "190001";
		else
			this.applyYm = applyYm;
	}
	
	public void setValue(String value) {
		this.value = value;		
	}
	
	public void setApplyYm(String applyYm) {
		this.applyYm = applyYm;
	}
	
	public long getId() {
		return id;
	}
	
	public String getName() {
		return name;
	}
	
	public String getValue() {
		return value;
	}
	
	public String getApplyYm() {
		return applyYm;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}
	
	public String getDesc() {
		return desc;
	}
	
	public static Integer getValue(String key, String ym, String defaultValue, boolean createIfNotExists) {
		Objectify ofy = ObjectifyService.begin();
		Query<BookConfiguration> q = ofy.query(BookConfiguration.class)
												.filter("name", key)
												.filter("applyYm <=" , ym)
												.order("-applyYm");
		BookConfiguration conf = q.get();
		if (conf == null && createIfNotExists) {
			conf = new BookConfiguration(key);
			ofy.put(conf);
		}
		
		int day = 1;
		String value = (String)conf.getValue();
		
		try {
			day = Integer.parseInt(value);
		} catch(NumberFormatException nfe) {			
		}
		
		return day;
		
	}
}
